import React, { Component } from "react";
import ProductTable from "../components/ProductTable";
import SearchBar from "../components/SearchBar";

export default class FilterableProductTable extends Component {
  constructor() {
    super();
    this.state = {
      list: [
        {
          category: "Sporting Goods",
          price: "$49.99",
          stocked: true,
          name: "Football",
        },
        {
          category: "Sporting Goods",
          price: "$9.99",
          stocked: true,
          name: "Baseball",
        },
        {
          category: "Sporting Goods",
          price: "$29.99",
          stocked: false,
          name: "Basketball",
        },
        {
          category: "Electronics",
          price: "$99.99",
          stocked: true,
          name: "iPod Touch",
        },
        {
          category: "Electronics",
          price: "$399.99",
          stocked: false,
          name: "iPhone 5",
        },
        {
          category: "Electronics",
          price: "$199.99",
          stocked: true,
          name: "Nexus 7",
        },
      ],
      arr: [], //分组的数据
    };
  }
  search = (flag, key) => {
    let list = [];
    //查找谁??
    if (flag) {
      list = this.state.list.filter(
        (item) =>
          item.stocked &&
          item.name.toLowerCase().indexOf(key.toLowerCase()) !== -1
      ); // 有货的
    } else {
      list = this.state.list.filter(
        (item) => item.name.toUpperCase().indexOf(key.toUpperCase()) !== -1
      ); //全部
    }

    //筛选
    let categoryList = Array.from(new Set(list.map((item) => item.category)));
    //["Sporting Goods","Electronics"]

    categoryList = categoryList.map((category) => {
      return {
        category,
        list: list.filter((info) => info.category === category),
      };
    });

    //  console.log(categoryList);
    this.setState({
      //重新整合数据
      arr: categoryList,
    });
  };

  componentDidMount() {
    //页面结构加载完成
    //对list进行分组处理
    let categoryList = Array.from(
      new Set(this.state.list.map((item) => item.category))
    );
    //["Sporting Goods","Electronics"]

    categoryList = categoryList.map((category) => {
      return {
        category,
        list: this.state.list.filter((info) => info.category === category),
      };
    });

    //  console.log(categoryList);
    this.setState({
      //重新整合数据
      arr: categoryList,
    });
  }
  render() {
    return (
      <div>
        <h3>商品查找</h3>
        <SearchBar search={this.search}></SearchBar>
        <ProductTable list={this.state.arr}></ProductTable>
      </div>
    );
  }
}
